<template>
  <el-card>
    <h1>{{ id ? "编辑" : "创建" }}班级</h1>
    <el-form
      :model="classForm"
      label-width="100px"
      ref="classFormRef"
      :rules="classFormRules"
    >
      <el-form-item
        label="班级编号"
        prop="classNum"
      >
        <el-input
          class="fiw"
          v-model.number="classForm.classNum"
        />
      </el-form-item>
      <el-form-item
        label="班级名字"
        prop="className"
      >
        <el-input
          class="fiw"
          v-model="classForm.className"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="save()"
        >
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  props: {
    id: {},
  },
  data() {
    return {
      classForm: {
        jf:0
      },
      classFormRules: {
        className: [
          { required: true, message: "请输入班级名称", trigger: 'blur'},
        ],
        classNum: [
          { required: true, message: "请输入班级编号", trigger: 'blur' },
          { type: "number", message: "请输入数字" }
        ],
        jf: [
          { required: true, message: "请输入班级积分", trigger: 'blur'},
          { type: "number", message: "请输入数字" }
        ],
      },
    };
  },
  created() {
    this.id && this.fetch();
  },

  methods: {
    async fetch() {
      const rs = await this.$http.get(`rest/classes/${this.id}`);
      this.classForm = rs.data;
      console.log(this);
    },
    async save() {
      console.log(this.form);
      let rs;
      if (this.id) {
        this.$refs.classFormRef.validate(async (valid) => {
          if (!valid) return;
          rs = await this.$http.put(`rest/classes/${this.id}`, this.classForm);
          if (rs.status !== 200) return;
          this.$message({
            message: "成功",
            type: "success",
          });
          this.$router.push({ path: "/class/list" });
        });
      } else {
        this.$refs.classFormRef.validate(async (valid) => {
          if (!valid) return;
          rs = await this.$http.post("rest/classes", this.classForm);
          if (rs.status !== 200) return;
          this.$message({
            message: "成功",
            type: "success",
          });
          this.$router.push({ path: "/class/list" });
        });
      }
      // if (rs.status !== 200) return;
      // this.$message({
      //   message: "成功",
      //   type: "success",
      // });
      // this.$router.push({ path: "/class/list" });
    },
  },
};
</script>

<style lang="scss" scoped>
.fiw {
  width: 200px;
}
.el-form {
  margin-top: 30px;
}
</style>
